#
# Copyright 2008 Google Inc. All Rights Reserved.

"""A module for managing station configuration in the AppEngine DataStore.

Contains AppEngine DataStore models for StationConfig and StationSource, along
with functions to add and remove them from the database.

  StationConfig: Configuration for a station.
  StationSource: A source for a station.
  GetStationListJSON(): Returns a JSON representation of the database state.
  CreateStation(label): Returns a new station with the given label.
  GetStationById(id): Returns a station from a key id
  AddSource(station, type, source): Add a new source to a station.
  DeleteStation(id): Delete the station with the given key id.
  DeleteSource(id): Delete the source with the given key id.
"""

__author__ = 'libra@google.com (Jasmine Langridge)'

import logging
from google.appengine.ext import db
from google.appengine.api import users


# AppEngine DataStore objects
class StationConfig(db.Model):

  label = db.StringProperty(required=True)


class StationSource(db.Model):

  station = db.ReferenceProperty(StationConfig, required=True)
  type = db.StringProperty(required=True, choices=set(['channel',
                                                       'playlist',
                                                       'category',
                                                       'feed',
                                                       'search']))
  source = db.StringProperty(required=True)


def GarbageCollect():
  sources = StationSource.all()
  for source in sources:
    try:
      if not source.station:
        source.delete()
    except:
      source.delete()


def GetStationConfigIterator():
  query = StationConfig.all()
  query.order('label')
  return query


def GetStationList():
  stations = GetStationConfigIterator()
  return [x for x in stations]


def GetStationListJSON():
  json = '['
  stations = GetStationConfigIterator()
  repeated = False
  for station in stations:
    if repeated:
      json += ',\n'
    repeated = True
    json += '{"label":"' + station.label + '","sources":['
    rep2 = False
    for source in station.stationsource_set:
      if rep2:
        json += ','
      rep2 = True
      json += '{\n"type":"' + source.type + '",'
      json += '"source":"' + source.source + '"}'
    json += ']}\n'
  json += ']\n'
  return json


def CreateStation(label):
  sc = StationConfig(label=label)
  sc.put()
  return sc


def GetStationById(id):
  return StationConfig.get_by_id(id)


def AddSource(station, type, source):
  StationSource(station=station, type=type, source=source).put()


def DeleteStation(id):
  station = GetStationById(id)
  if station:
    station.delete()
    logging.info('Deleted station: ' + str(id))
    GarbageCollect()
  else:
    logging.warning('Unknown station key')


def DeleteSource(id):
  source = StationSource.get_by_id(id)
  if source:
    source.delete()
    logging.info('Deleted source: ' + str(id))
    # Don't need to garbage collect after deleting a source
  else:
    logging.warning('Unknown source key')
